/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.rsa.management.key;

import com.asialjim.encommunicate.base.rsa.key.RSAClientKey;
import com.asialjim.encommunicate.base.rsa.key.RSAServerKey;
import com.asialjim.encommunicate.rsa.management.pojo.AppEnDecryptInfo;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.validation.annotation.Validated;

import java.util.Objects;
import java.util.Set;

/**
 * RSA 密钥对数据仓库
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/27, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
@Validated
public interface RSAKeyRepository {

    /**
     * 添加，或者修改 应用 加解密配置信息
     * <br/>若：数据仓库中已经存在此应用，则修改，若不存在，则添加
     * <br/> 实现类自行实现持久层代码（包括数据库表设计，本地文件存储等各种方式）
     *
     * @param appEnDecryptInfo {@link AppEnDecryptInfo 应用加解密配置信息}
     * @return {@link AppEnDecryptInfo 修改后的配置信息}
     * @since 2023/2/28
     */
    @SuppressWarnings("UnusedReturnValue")
    AppEnDecryptInfo modify(@Valid @NotNull(message = "应用加解密配置信息不能为空") AppEnDecryptInfo appEnDecryptInfo);

    Set<AppEnDecryptInfo> infos();

    AppEnDecryptInfo enDecryptInfo(String appid);

    /**
     * 查询服务端密钥对
     *
     * @param appid {@link String appid}
     * @return {@link RSAServerKey 服务端密钥对}
     * @since 2023/2/27
     */
    default RSAServerKey serverKey(String appid){
        AppEnDecryptInfo info = enDecryptInfo(appid);
        if (Objects.isNull(info))
            return null;

        return RSAServerKey.builder().priKey(info.getServerPriKey()).pubKey(info.getServerPubKey()).build();
    }

    /**
     * 查询客户端密钥对
     *
     * @param appid {@link String appid}
     * @return {@link RSAClientKey 客户端密钥对}
     * @since 2023/2/27
     */
    default RSAClientKey clientKey(String appid){
        AppEnDecryptInfo info = enDecryptInfo(appid);
        if (Objects.isNull(info))
            return null;

        return RSAClientKey.builder().appid(appid).priKey(info.getClientPriKey()).pubKey(info.getClientPubKey()).build();
    }
}